package thread;

import java.util.Random;

//取钱人
public class Taker extends Thread {
    Accout ac;

    public Taker(String name, Accout ac) {
        super(name);
        this.ac = ac;
    }

    @Override
    public void run() {
        Random r = new Random();
        while (true) {
            int m = r.nextInt(300);
            System.out.println("现在" + super.getName() + "取钱 " + m + "元,当前余额是" + ac.getMoney());

            synchronized (ac) {
                try {
                    while (ac.getMoney() < m) {//!!!!
                        System.out.println("现在" + super.getName() + "取钱 " + m + "元,当前余额是" + ac.getMoney()+",余额不足,等着...");

                        ac.wait();
                        //
                        System.out.println("现在 " + super.getName() + " 被唤醒,准备取钱"+m+"元...");
                    }
                    ac.withDraw(m);
                    System.out.println(super.getName() + "取钱 " + m + "元成功,当前余额是" + ac.getMoney());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
